{% extends 'base.html' %}
{% load static %}

{% block title %}文件管理 - CFS Web System{% endblock %}

{% block page_type %}file-manager{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">文件管理</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 页面标题 -->
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-folder-open me-2"></i>文件管理</h2>
            <div class="btn-group">
                <button type="button" class="btn btn-outline-primary" onclick="refreshFiles()">
                    <i class="fas fa-sync-alt"></i> 刷新
                </button>
                <a href="{% url 'data_processing:data_generation' %}" class="btn btn-success">
                    <i class="fas fa-upload"></i> 上传文件
                </a>
                <button type="button" class="btn btn-outline-danger" onclick="batchDelete()" id="batch-delete-btn" style="display: none;">
                    <i class="fas fa-trash"></i> 批量删除
                </button>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 文件统计 -->
    <div class="col-12 mb-4">
        <div class="row" id="file-stats">
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-primary">
                            <i class="fas fa-file"></i>
                        </div>
                        <h3 class="stat-number" id="total-files">0</h3>
                        <p class="stat-label">总文件数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-success">
                            <i class="fas fa-file-excel"></i>
                        </div>
                        <h3 class="stat-number" id="excel-files">0</h3>
                        <p class="stat-label">Excel文件</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-info">
                            <i class="fas fa-file-csv"></i>
                        </div>
                        <h3 class="stat-number" id="csv-files">0</h3>
                        <p class="stat-label">CSV文件</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card stat-card">
                    <div class="card-body text-center">
                        <div class="stat-icon bg-warning">
                            <i class="fas fa-hdd"></i>
                        </div>
                        <h3 class="stat-number" id="total-size">0</h3>
                        <p class="stat-label">总大小</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 文件列表 -->
    <div class="col-lg-9">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-list me-2"></i>文件列表
                    </h5>
                    <div class="d-flex align-items-center">
                        <!-- 搜索框 -->
                        <div class="input-group input-group-sm me-3" style="width: 250px;">
                            <input type="text" class="form-control" id="search-input" placeholder="搜索文件...">
                            <button class="btn btn-outline-secondary" type="button" onclick="searchFiles()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                        
                        <!-- 视图切换 -->
                        <div class="btn-group btn-group-sm me-3">
                            <button type="button" class="btn btn-outline-secondary view-btn active" data-view="list">
                                <i class="fas fa-list"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary view-btn" data-view="grid">
                                <i class="fas fa-th"></i>
                            </button>
                        </div>
                        
                        <!-- 排序 -->
                        <select class="form-select form-select-sm" id="sort-select" style="width: auto;">
                            <option value="-created_at">最新上传</option>
                <option value="created_at">最早上传</option>
                            <option value="original_name">文件名 A-Z</option>
                            <option value="-original_name">文件名 Z-A</option>
                            <option value="-file_size">大小 大-小</option>
                            <option value="file_size">大小 小-大</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="card-body p-0">
                <!-- 过滤器 -->
                <div class="filter-bar p-3 border-bottom">
                    <div class="row align-items-center">
                        <div class="col-md-3">
                            <label class="form-label mb-1">文件类型:</label>
                            <select class="form-select form-select-sm" id="type-filter">
                                <option value="">全部类型</option>
                                <option value="source">源文件</option>
                                <option value="template">模板文件</option>
                                <option value="result">结果文件</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label mb-1">文件格式:</label>
                            <select class="form-select form-select-sm" id="format-filter">
                                <option value="">全部格式</option>
                                <option value="xlsx">Excel (.xlsx)</option>
                                <option value="xls">Excel (.xls)</option>
                                <option value="csv">CSV (.csv)</option>
                                <option value="txt">文本 (.txt)</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label mb-1">关联模板:</label>
                            <select class="form-select form-select-sm" id="template-filter">
                                <option value="">全部模板</option>
                                <!-- 模板选项将通过AJAX加载 -->
                            </select>
                        </div>
                        <div class="col-md-3">
                            <div class="d-flex align-items-end">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="select-all">
                                    <label class="form-check-label" for="select-all">
                                        全选
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 文件列表容器 -->
                <div id="file-list-container">
                    <!-- 文件列表将通过AJAX加载 -->
                </div>
                
                <!-- 分页 -->
                <div class="p-3 border-top" id="pagination-container">
                    <!-- 分页将通过JavaScript生成 -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 文件详情 -->
    <div class="col-lg-3">
        <div class="card" id="file-detail-card" style="display: none;">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-info-circle me-2"></i>文件详情
                </h6>
            </div>
            <div class="card-body" id="file-detail-content">
                <!-- 文件详情将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 快速操作 -->
        <div class="card mt-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="{% url 'data_processing:data_generation' %}" class="btn btn-primary btn-sm">
                        <i class="fas fa-upload"></i> 上传文件
                    </a>
                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="exportFileList()">
                        <i class="fas fa-download"></i> 导出列表
                    </button>
                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="cleanupFiles()">
                        <i class="fas fa-broom"></i> 清理文件
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 存储信息 -->
        <div class="card mt-4">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-chart-pie me-2"></i>存储信息
                </h6>
            </div>
            <div class="card-body">
                <div class="storage-info">
                    <div class="d-flex justify-content-between mb-2">
                        <span>已使用:</span>
                        <span id="used-storage">--</span>
                    </div>
                    <div class="progress mb-3" style="height: 8px;">
                        <div class="progress-bar" id="storage-progress" style="width: 0%"></div>
                    </div>
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="storage-metric">
                                <div class="metric-value" id="file-count">--</div>
                                <div class="metric-label">文件数</div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="storage-metric">
                                <div class="metric-value" id="avg-size">--</div>
                                <div class="metric-label">平均大小</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 文件预览模态框 -->
<div class="modal fade" id="filePreviewModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye me-2"></i>文件预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h6 id="preview-file-name">文件名</h6>
                        <small class="text-muted" id="preview-file-info">文件信息</small>
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-primary" onclick="downloadPreviewFile()">
                            <i class="fas fa-download"></i> 下载
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="refreshPreview()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                    </div>
                </div>
                <div id="preview-content">
                    <!-- 预览内容将通过JavaScript加载 -->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 批量操作模态框 -->
<div class="modal fade" id="batchOperationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-tasks me-2"></i>批量操作
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>已选择 <span id="selected-count">0</span> 个文件</p>
                
                <div class="mb-3">
                    <label class="form-label">操作类型:</label>
                    <select class="form-select" id="batch-operation-type">
                        <option value="delete">删除文件</option>
                        <option value="move">移动到模板</option>
                        <option value="copy">复制到模板</option>
                        <option value="export">导出文件</option>
                    </select>
                </div>
                
                <div class="mb-3" id="target-template-group" style="display: none;">
                    <label class="form-label">目标模板:</label>
                    <select class="form-select" id="target-template">
                        <option value="">选择模板</option>
                        <!-- 模板选项将通过AJAX加载 -->
                    </select>
                </div>
                
                <div class="alert alert-warning" id="operation-warning" style="display: none;">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <span id="warning-message"></span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="executeBatchOperation()">
                    <i class="fas fa-check"></i> 执行操作
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 页面状态管理
const pageState = {
    currentView: 'list',
    currentPage: 1,
    pageSize: 20,
    selectedFiles: new Set(),
    currentFile: null,
    filters: {
        search: '',
        type: '',
        format: '',
        template: '',
        sort: '-created_at'
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeFileManager();
});

// 初始化文件管理页面
function initializeFileManager() {
    // 加载文件列表
    loadFiles();
    
    // 加载文件统计
    loadFileStats();
    
    // 加载模板选项
    loadTemplateOptions();
    
    // 绑定事件
    bindEvents();
}

// 绑定事件
function bindEvents() {
    // 搜索框回车事件
    document.getElementById('search-input').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchFiles();
        }
    });
    
    // 排序变化事件
    document.getElementById('sort-select').addEventListener('change', function() {
        pageState.filters.sort = this.value;
        loadFiles();
    });
    
    // 过滤器变化事件
    ['type-filter', 'format-filter', 'template-filter'].forEach(id => {
        document.getElementById(id).addEventListener('change', function() {
            const filterName = id.replace('-filter', '');
            pageState.filters[filterName] = this.value;
            pageState.currentPage = 1;
            loadFiles();
        });
    });
    
    // 视图切换事件
    const viewBtns = document.querySelectorAll('.view-btn');
    viewBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            setView(this.dataset.view);
        });
    });
    
    // 全选事件
    document.getElementById('select-all').addEventListener('change', function() {
        toggleSelectAll(this.checked);
    });
    
    // 批量操作类型变化事件
    document.getElementById('batch-operation-type').addEventListener('change', function() {
        updateBatchOperationUI(this.value);
    });
}

// 加载文件列表
function loadFiles() {
    const container = document.getElementById('file-list-container');
    CFS.utils.showLoading(container, '加载文件列表...');
    
    const params = new URLSearchParams({
        page: pageState.currentPage,
        page_size: pageState.pageSize,
        ...pageState.filters
    });
    
    fetch(`/file-manager/ajax/files/?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFileList(data.files, data.pagination);
            } else {
                container.innerHTML = '<div class="alert alert-danger m-3">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger m-3">加载失败: ' + error.message + '</div>';
        });
}

// 渲染文件列表
function renderFileList(files, pagination) {
    const container = document.getElementById('file-list-container');
    
    if (files.length === 0) {
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-folder-open fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">暂无文件</h5>
                <p class="text-muted mb-3">还没有上传任何文件。</p>
                <a href="/data-processing/generation/" class="btn btn-primary">
                    <i class="fas fa-upload"></i> 数据生成
                </a>
            </div>
        `;
        return;
    }
    
    if (pageState.currentView === 'list') {
        renderListView(files);
    } else {
        renderGridView(files);
    }
    
    // 渲染分页
    renderPagination(pagination);
}

// 渲染列表视图
function renderListView(files) {
    const container = document.getElementById('file-list-container');
    
    const html = `
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th width="40">
                            <input type="checkbox" class="form-check-input" id="table-select-all">
                        </th>
                        <th>文件名</th>
                        <th>类型</th>
                        <th>大小</th>
                        <th>上传时间</th>
                        <th>关联模板</th>
                        <th width="120">操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${files.map(file => `
                        <tr class="file-row ${pageState.selectedFiles.has(file.id) ? 'selected' : ''}" 
                            data-file-id="${file.id}" onclick="selectFile('${file.id}', event)">
                            <td>
                                <input type="checkbox" class="form-check-input file-checkbox" 
                                       value="${file.id}" ${pageState.selectedFiles.has(file.id) ? 'checked' : ''}
                                       onclick="event.stopPropagation();">
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="${getFileIcon(file.file_extension)} me-2"></i>
                                    <div>
                                        <div class="fw-bold">${file.original_name}</div>
                                        <small class="text-muted">${file.file_extension.toUpperCase()}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-${getFileTypeColor(file.file_type)}">
                                    ${getFileTypeText(file.file_type)}
                                </span>
                            </td>
                            <td>${CFS.utils.formatFileSize(file.file_size)}</td>
                            <td>${CFS.utils.formatDateTime(file.created_at)}</td>
                            <td>${file.template_name || '-'}</td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <button type="button" class="btn btn-outline-primary" 
                                            onclick="previewFile('${file.id}'); event.stopPropagation();">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-success" 
                                            onclick="downloadFile('${file.id}'); event.stopPropagation();">
                                        <i class="fas fa-download"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-danger" 
                                            onclick="deleteFile('${file.id}'); event.stopPropagation();">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        </div>
    `;
    
    container.innerHTML = html;
    
    // 绑定表格全选事件
    document.getElementById('table-select-all').addEventListener('change', function() {
        toggleSelectAll(this.checked);
    });
    
    // 绑定文件选择事件
    const checkboxes = container.querySelectorAll('.file-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            toggleFileSelection(this.value, this.checked);
        });
    });
}

// 渲染网格视图
function renderGridView(files) {
    const container = document.getElementById('file-list-container');
    
    const html = `
        <div class="row p-3">
            ${files.map(file => `
                <div class="col-md-4 col-lg-3 mb-3">
                    <div class="card file-card ${pageState.selectedFiles.has(file.id) ? 'selected' : ''}" 
                         data-file-id="${file.id}" onclick="selectFile('${file.id}', event)">
                        <div class="card-body text-center">
                            <div class="position-relative">
                                <input type="checkbox" class="form-check-input position-absolute top-0 start-0 file-checkbox" 
                                       value="${file.id}" ${pageState.selectedFiles.has(file.id) ? 'checked' : ''}
                                       onclick="event.stopPropagation();">
                                <i class="${getFileIcon(file.file_extension)} fa-3x text-primary mb-3"></i>
                            </div>
                            <h6 class="card-title" title="${file.original_name}">
                                ${file.original_name.length > 15 ? file.original_name.substring(0, 15) + '...' : file.original_name}
                            </h6>
                            <p class="card-text">
                                <span class="badge bg-${getFileTypeColor(file.file_type)} mb-1">
                                    ${getFileTypeText(file.file_type)}
                                </span><br>
                                <small class="text-muted">${CFS.utils.formatFileSize(file.file_size)}</small>
                            </p>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-outline-primary" 
                                        onclick="previewFile('${file.id}'); event.stopPropagation();">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button type="button" class="btn btn-outline-success" 
                                        onclick="downloadFile('${file.id}'); event.stopPropagation();">
                                    <i class="fas fa-download"></i>
                                </button>
                                <button type="button" class="btn btn-outline-danger" 
                                        onclick="deleteFile('${file.id}'); event.stopPropagation();">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('')}
        </div>
    `;
    
    container.innerHTML = html;
    
    // 绑定文件选择事件
    const checkboxes = container.querySelectorAll('.file-checkbox');
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            toggleFileSelection(this.value, this.checked);
        });
    });
}

// 渲染分页
function renderPagination(pagination) {
    const container = document.getElementById('pagination-container');
    
    if (pagination.total_pages <= 1) {
        container.innerHTML = '';
        return;
    }
    
    const html = `
        <div class="d-flex justify-content-between align-items-center">
            <div>
                显示 ${pagination.start_index} - ${pagination.end_index} 条，共 ${pagination.total_count} 条
            </div>
            <nav>
                <ul class="pagination pagination-sm mb-0">
                    <li class="page-item ${!pagination.has_previous ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${pagination.current_page - 1}); return false;">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                    ${generatePageNumbers(pagination).map(page => `
                        <li class="page-item ${page === pagination.current_page ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="changePage(${page}); return false;">
                                ${page}
                            </a>
                        </li>
                    `).join('')}
                    <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${pagination.current_page + 1}); return false;">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    `;
    
    container.innerHTML = html;
}

// 生成页码数组
function generatePageNumbers(pagination) {
    const pages = [];
    const current = pagination.current_page;
    const total = pagination.total_pages;
    
    // 显示当前页前后2页
    const start = Math.max(1, current - 2);
    const end = Math.min(total, current + 2);
    
    for (let i = start; i <= end; i++) {
        pages.push(i);
    }
    
    return pages;
}

// 加载文件统计
function loadFileStats() {
    fetch('/file-manager/ajax/stats/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateFileStats(data.stats);
            }
        })
        .catch(error => {
            console.error('加载文件统计失败:', error);
        });
}

// 更新文件统计
function updateFileStats(stats) {
    document.getElementById('total-files').textContent = stats.total_files || 0;
    document.getElementById('excel-files').textContent = stats.excel_files || 0;
    document.getElementById('csv-files').textContent = stats.csv_files || 0;
    document.getElementById('total-size').textContent = CFS.utils.formatFileSize(stats.total_size || 0);
    
    // 更新存储信息
    document.getElementById('used-storage').textContent = CFS.utils.formatFileSize(stats.total_size || 0);
    document.getElementById('file-count').textContent = stats.total_files || 0;
    document.getElementById('avg-size').textContent = CFS.utils.formatFileSize(stats.avg_size || 0);
    
    // 更新存储进度条（假设最大存储为10GB）
    const maxStorage = 10 * 1024 * 1024 * 1024; // 10GB
    const usagePercent = Math.min(100, (stats.total_size / maxStorage) * 100);
    document.getElementById('storage-progress').style.width = usagePercent + '%';
}

// 加载模板选项
function loadTemplateOptions() {
    fetch('/api/template-management/templates/')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateTemplateOptions(data.templates);
            }
        })
        .catch(error => {
            console.error('加载模板选项失败:', error);
        });
}

// 更新模板选项
function updateTemplateOptions(templates) {
    const selects = ['template-filter', 'target-template'];
    
    selects.forEach(selectId => {
        const select = document.getElementById(selectId);
        if (select) {
            // 保留第一个选项
            const firstOption = select.firstElementChild;
            select.innerHTML = '';
            select.appendChild(firstOption);
            
            // 添加模板选项
            templates.forEach(template => {
                const option = document.createElement('option');
                option.value = template.id;
                option.textContent = template.name;
                select.appendChild(option);
            });
        }
    });
}

// 搜索文件
function searchFiles() {
    pageState.filters.search = document.getElementById('search-input').value.trim();
    pageState.currentPage = 1;
    loadFiles();
}

// 设置视图
function setView(view) {
    pageState.currentView = view;
    
    // 更新按钮状态
    const viewBtns = document.querySelectorAll('.view-btn');
    viewBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.view === view);
    });
    
    // 重新渲染列表
    loadFiles();
}

// 选择文件
function selectFile(fileId, event) {
    if (event && event.target.type === 'checkbox') {
        return; // 如果点击的是复选框，不处理
    }
    
    pageState.currentFile = fileId;
    
    // 显示文件详情
    document.getElementById('file-detail-card').style.display = 'block';
    loadFileDetail(fileId);
}

// 加载文件详情
function loadFileDetail(fileId) {
    const container = document.getElementById('file-detail-content');
    CFS.utils.showLoading(container, '加载文件详情...');
    
    fetch(`/file-manager/ajax/files/${fileId}/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFileDetail(data.file);
            } else {
                container.innerHTML = '<div class="alert alert-danger">加载失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">加载失败: ' + error.message + '</div>';
        });
}

// 渲染文件详情
function renderFileDetail(file) {
    const container = document.getElementById('file-detail-content');
    
    const html = `
        <div class="text-center mb-3">
            <i class="${getFileIcon(file.file_extension)} fa-3x text-primary mb-2"></i>
            <h6>${file.original_name}</h6>
            <span class="badge bg-${getFileTypeColor(file.file_type)}">
                ${getFileTypeText(file.file_type)}
            </span>
        </div>
        
        <table class="table table-sm">
            <tr><td>文件大小:</td><td>${CFS.utils.formatFileSize(file.file_size)}</td></tr>
            <tr><td>文件格式:</td><td>${file.file_extension.toUpperCase()}</td></tr>
            <tr><td>上传时间:</td><td>${CFS.utils.formatDateTime(file.created_at)}</td></tr>
            <tr><td>关联模板:</td><td>${file.template_name || '无'}</td></tr>
            <tr><td>下载次数:</td><td>${file.download_count || 0}</td></tr>
        </table>
        
        ${file.description ? `
            <div class="mt-3">
                <h6>描述</h6>
                <p class="text-muted">${file.description}</p>
            </div>
        ` : ''}
        
        <div class="d-grid gap-2 mt-3">
            <button type="button" class="btn btn-primary btn-sm" onclick="previewFile('${file.id}')">
                <i class="fas fa-eye"></i> 预览文件
            </button>
            <button type="button" class="btn btn-success btn-sm" onclick="downloadFile('${file.id}')">
                <i class="fas fa-download"></i> 下载文件
            </button>
            <button type="button" class="btn btn-outline-warning btn-sm" onclick="editFile('${file.id}')">
                <i class="fas fa-edit"></i> 编辑信息
            </button>
            <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteFile('${file.id}')">
                <i class="fas fa-trash"></i> 删除文件
            </button>
        </div>
    `;
    
    container.innerHTML = html;
}

// 切换文件选择
function toggleFileSelection(fileId, selected) {
    if (selected) {
        pageState.selectedFiles.add(fileId);
    } else {
        pageState.selectedFiles.delete(fileId);
    }
    
    updateSelectionUI();
}

// 切换全选
function toggleSelectAll(selectAll) {
    const checkboxes = document.querySelectorAll('.file-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll;
        toggleFileSelection(checkbox.value, selectAll);
    });
    
    // 更新表格全选状态
    const tableSelectAll = document.getElementById('table-select-all');
    if (tableSelectAll) {
        tableSelectAll.checked = selectAll;
    }
}

// 更新选择UI
function updateSelectionUI() {
    const selectedCount = pageState.selectedFiles.size;
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    
    if (selectedCount > 0) {
        batchDeleteBtn.style.display = 'inline-block';
        batchDeleteBtn.innerHTML = `<i class="fas fa-trash"></i> 批量删除 (${selectedCount})`;
    } else {
        batchDeleteBtn.style.display = 'none';
    }
    
    // 更新文件行选中状态
    const fileRows = document.querySelectorAll('.file-row, .file-card');
    fileRows.forEach(row => {
        const fileId = row.dataset.fileId;
        row.classList.toggle('selected', pageState.selectedFiles.has(fileId));
    });
}

// 预览文件
function previewFile(fileId) {
    const modal = new bootstrap.Modal(document.getElementById('filePreviewModal'));
    const container = document.getElementById('preview-content');
    
    CFS.utils.showLoading(container, '加载文件预览...');
    modal.show();
    
    fetch(`/file-manager/ajax/files/${fileId}/preview/`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFilePreview(data.preview, data.file);
            } else {
                container.innerHTML = '<div class="alert alert-danger">预览失败: ' + data.error + '</div>';
            }
        })
        .catch(error => {
            container.innerHTML = '<div class="alert alert-danger">预览失败: ' + error.message + '</div>';
        });
}

// 渲染文件预览
function renderFilePreview(preview, file) {
    document.getElementById('preview-file-name').textContent = file.original_name;
    document.getElementById('preview-file-info').textContent = 
        `${file.file_extension.toUpperCase()} | ${CFS.utils.formatFileSize(file.file_size)} | ${CFS.utils.formatDateTime(file.created_at)}`;
    
    const container = document.getElementById('preview-content');
    
    if (preview.type === 'table') {
        // 表格预览
        const html = `
            <div class="table-responsive">
                <table class="table table-sm table-bordered">
                    <thead class="table-light">
                        <tr>
                            ${preview.headers.map(header => `<th>${header}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${preview.data.map(row => `
                            <tr>
                                ${row.map(cell => `<td>${cell || ''}</td>`).join('')}
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            ${preview.total_rows > preview.data.length ? `
                <div class="alert alert-info mt-3">
                    <i class="fas fa-info-circle me-2"></i>
                    显示前 ${preview.data.length} 行，共 ${preview.total_rows} 行数据
                </div>
            ` : ''}
        `;
        container.innerHTML = html;
    } else if (preview.type === 'text') {
        // 文本预览
        container.innerHTML = `
            <pre class="bg-light p-3 rounded" style="max-height: 400px; overflow-y: auto;">${preview.content}</pre>
        `;
    } else {
        // 不支持预览
        container.innerHTML = `
            <div class="text-center py-5">
                <i class="fas fa-file fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">无法预览此文件类型</h5>
                <p class="text-muted">请下载文件查看内容</p>
            </div>
        `;
    }
}

// 下载文件
function downloadFile(fileId) {
    window.open(`/file-manager/download/${fileId}/`, '_blank');
}

// 删除文件
function deleteFile(fileId) {
    if (!confirm('确定要删除这个文件吗？此操作不可恢复。')) {
        return;
    }
    
    fetch(`/file-manager/ajax/files/${fileId}/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('文件已删除', 'success');
            loadFiles();
            loadFileStats();
            
            // 如果删除的是当前选中的文件，隐藏详情卡片
            if (pageState.currentFile === fileId) {
                document.getElementById('file-detail-card').style.display = 'none';
                pageState.currentFile = null;
            }
            
            // 从选中列表中移除
            pageState.selectedFiles.delete(fileId);
            updateSelectionUI();
        } else {
            CFS.utils.showNotification('删除失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('删除失败: ' + error.message, 'error');
    });
}

// 批量删除
function batchDelete() {
    if (pageState.selectedFiles.size === 0) {
        CFS.utils.showNotification('请先选择要删除的文件', 'warning');
        return;
    }
    
    document.getElementById('selected-count').textContent = pageState.selectedFiles.size;
    document.getElementById('batch-operation-type').value = 'delete';
    updateBatchOperationUI('delete');
    
    const modal = new bootstrap.Modal(document.getElementById('batchOperationModal'));
    modal.show();
}

// 更新批量操作UI
function updateBatchOperationUI(operationType) {
    const targetTemplateGroup = document.getElementById('target-template-group');
    const operationWarning = document.getElementById('operation-warning');
    const warningMessage = document.getElementById('warning-message');
    
    // 隐藏所有可选项
    targetTemplateGroup.style.display = 'none';
    operationWarning.style.display = 'none';
    
    switch (operationType) {
        case 'delete':
            operationWarning.style.display = 'block';
            warningMessage.textContent = '删除操作不可恢复，请确认后执行。';
            break;
        case 'move':
        case 'copy':
            targetTemplateGroup.style.display = 'block';
            break;
        case 'export':
            operationWarning.style.display = 'block';
            warningMessage.textContent = '将导出选中的文件为压缩包。';
            break;
    }
}

// 执行批量操作
function executeBatchOperation() {
    const operationType = document.getElementById('batch-operation-type').value;
    const selectedFiles = Array.from(pageState.selectedFiles);
    
    if (selectedFiles.length === 0) {
        CFS.utils.showNotification('请先选择文件', 'warning');
        return;
    }
    
    const data = {
        operation: operationType,
        file_ids: selectedFiles
    };
    
    if (operationType === 'move' || operationType === 'copy') {
        const targetTemplate = document.getElementById('target-template').value;
        if (!targetTemplate) {
            CFS.utils.showNotification('请选择目标模板', 'warning');
            return;
        }
        data.target_template_id = targetTemplate;
    }
    
    fetch('/file-manager/ajax/batch-operation/', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(`批量操作完成，处理了 ${data.count} 个文件`, 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('batchOperationModal'));
            modal.hide();
            
            // 清空选择
            pageState.selectedFiles.clear();
            updateSelectionUI();
            
            // 刷新列表
            loadFiles();
            loadFileStats();
        } else {
            CFS.utils.showNotification('批量操作失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('批量操作失败: ' + error.message, 'error');
    });
}

// 刷新文件列表
function refreshFiles() {
    loadFiles();
    loadFileStats();
    CFS.utils.showNotification('已刷新', 'info');
}

// 导出文件列表
function exportFileList() {
    window.open('/file-manager/export/', '_blank');
}

// 清理文件
function cleanupFiles() {
    if (!confirm('确定要清理无用文件吗？这将删除所有未关联模板的文件。')) {
        return;
    }
    
    fetch('/file-manager/ajax/cleanup/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(`清理完成，删除了 ${data.count} 个文件`, 'success');
            loadFiles();
            loadFileStats();
        } else {
            CFS.utils.showNotification('清理失败: ' + data.error, 'error');
        }
    })
    .catch(error => {
        CFS.utils.showNotification('清理失败: ' + error.message, 'error');
    });
}

// 编辑文件信息
function editFile(fileId) {
    // 实现文件信息编辑功能
    console.log('编辑文件:', fileId);
}

// 切换页面
function changePage(page) {
    pageState.currentPage = page;
    loadFiles();
}

// 下载预览文件
function downloadPreviewFile() {
    if (pageState.currentFile) {
        downloadFile(pageState.currentFile);
    }
}

// 刷新预览
function refreshPreview() {
    if (pageState.currentFile) {
        previewFile(pageState.currentFile);
    }
}

// 工具函数
function getFileIcon(extension) {
    const icons = {
        'xlsx': 'fas fa-file-excel text-success',
        'xls': 'fas fa-file-excel text-success',
        'csv': 'fas fa-file-csv text-info',
        'txt': 'fas fa-file-alt text-secondary',
        'pdf': 'fas fa-file-pdf text-danger',
        'doc': 'fas fa-file-word text-primary',
        'docx': 'fas fa-file-word text-primary'
    };
    return icons[extension.toLowerCase()] || 'fas fa-file text-muted';
}

function getFileTypeColor(type) {
    const colors = {
        'source': 'primary',
        'template': 'success',
        'result': 'warning',
        'other': 'secondary'
    };
    return colors[type] || 'secondary';
}

function getFileTypeText(type) {
    const texts = {
        'source': '源文件',
        'template': '模板文件',
        'result': '结果文件',
        'other': '其他'
    };
    return texts[type] || '未知';
}
</script>
{% endblock %}